import Vuex from 'vuex'
import Vue from 'vue'
import  request  from '../common/ajax/request'

Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    userInfo: undefined, // 会员全部信息
    companyInfo: undefined, // 公司信息
    popQueue: new Set() // 弹窗队列
  },
  // 仅 过滤数据
  getters: {
    // 获取用户消息
    userInfo (state, getters) {
      return state.userInfo
    },
    // 获取公司信息
    companyInfo (state) {
      return state.companyInfo
    },

    // 获取全部门店列表
    shopList () {

    },
    // 用户信息和公司信息获取完毕, 依赖信息加载完后才能允许往下执行
    states ({userInfo, companyInfo}) {
      if (userInfo === undefined || companyInfo === undefined) { // 等待
        return 2
      } else if (userInfo === null ||  companyInfo === null) { // 失败
        return 0
      } else if(userInfo && companyInfo) { // 成功
        return 1
      }
    }
  },
  /*
  * 更改 Vuex 的 store 中的状态的唯一方法是提交 mutation, Mutation 必须是同步函数
  * store.commit('increment')
  * */
  // 突变，转变
  mutations: {
    setUserInfo (state, payload) {
      state.userInfo = payload
    },
    setCompanyInfo (state, payload) {
      state.companyInfo = payload
    },
    addPop (state, payload) {
      state.popQueue.add(payload)
    },
    closePop ({popQueue}, payload) {
      popQueue.delete(payload)
      payload()
    },
    closePopQueue ({popQueue}) {
      popQueue.forEach(i => {
        i()
        popQueue.delete(i)
      })
    }
  },
  /*
  * store.dispatch('increment', products)
  * */
  // Action 提交的是 mutation，而不是直接变更状态, Action 通常是异步的(用于处理异步)
  actions: {
    async updateUserInfo ({commit}) {
      try {
        const r = await $g.userInfoAsync(true)
        commit('setUserInfo', r || null)
      } catch (e) {
        commit('setUserInfo', null)
        throw e
      }
    },
    async updateCompanyInfo ({commit}) {
      try {
        const r = await $g.companyInfoAsync(true)
        document.title = r.companyName
        commit('setCompanyInfo', r || null)
      } catch (e) {
        commit('setCompanyInfo', null)
        throw e
      }
    }
  }
})

window.store = store
export default store
